# TODO: Add comment
# 
# Author: broken
###############################################################################
library(raster)
library(base)
library(gstat)
library(stringr)

path= "/var/www/html/fimo/apom/Resample/SatResampMOD04_Daily/"
shap=shapefile("/home/phamha/BDNEN/VNM_adm0.shp")

a=c(2009,2010,2011,2012,2013,2014)
#a=c(2009,2010)
for (i in 1:2) {
	inputPath=paste(path,a[i],sep="")

	listFile = list.files(path = inputPath,pattern="_10km.tif$",full.names = TRUE,recursive=TRUE)
	listSize=length(listFile)
	for(j in 1:listSize){
		
		
		#check file exist
		
		rasterFile=raster(listFile[j])
		
		#get total pixel in VN
		#raster2=rasterFile
		#rasterValues2=values(raster2)
		#total2=ncell(rasterValues2)
	
		#raster2[1:total2]=100
		#raster2=crop(raster2,shap)
		#raster2=mask(raster2,shap)
		#rasterValues2=values(raster2)
		#total_pixcel2=sum(!is.na(rasterValues2))
		
		#get valuable pixel in VN
		rasterFile=crop(rasterFile,shap)
		rasterFile=mask(rasterFile,shap)
	
		outFile=paste(substr(listFile[j],1,102),"_crop.tif",sep="")
		writeRaster(rasterFile,filename=outFile,format="GTiff")
		print(outFile)
	
	}
}
print("done")
